﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using RLPUR.Common;
using RLPUR.Models;

namespace RLPUR.Web
{
    public partial class PayInvoice : LocalPage
    {
        /// <summary>
        /// 页面加载
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                #region 验证权限

                #endregion

                #region 获取参数

                #endregion

                //初始化
                this.Initialize();
            }

            #region 页面标题

            this.Title = PageTitle.Text;

            #endregion

            #region 页面要素


            #endregion
        }

        #region 初始化

        /// <summary>
        /// 初始化
        /// </summary>
        private void Initialize()
        {
            #region 页面内容

            OrNo.Text = string.Empty;
            RTNo.Text = string.Empty;
            PrNo.Text = string.Empty;
            VenNo.Text = string.Empty;
            VenName.Text = string.Empty;
            DateFrom.Text = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd");
            DateTo.Text = DateTime.Now.ToString("yyyy-MM-dd");

            IsKp.SelectedIndex = -1;
            SaveButton.Enabled = false;
            divInvoice.Visible = false;
            panelTon.Visible = false;

            #endregion

            //绑定列表
            //this.BindList();
        }

        #endregion

        #region 绑定数据

        /// <summary>
        /// 绑定列表
        /// </summary>

        private void BindList()
        {
            if (IsTon.Checked) //按吨位结算
            {
                if (OrNo.Text.Trim().Length == 0 && RTNo.Text.Trim().Length == 0 && PrNo.Text.Trim().Length == 0)
                {
                    this.ShowWarningMessage("请输入工令号或收货单号或订单号码");
                    return;
                }
            }

            using (PurProvider purProvider = new PurProvider())
            {
                string dateFrom = LocalGlobal.ConvertDateFormat(DateFrom.Text.Trim()).ToString("yyyyMMdd");
                string dateTo = LocalGlobal.ConvertDateFormat(DateTo.Text.Trim()).ToString("yyyyMMdd");
                int kpType = IsKp.SelectedValue == "N" ? 1 : 0;
                DataTable table = purProvider.GetPrInvoiceList(OrNo.Text.Trim(), RTNo.Text.Trim(), PrNo.Text.Trim(), dateFrom, dateTo, VenNo.Text.Trim(), VenName.Text.Trim(), kpType, IsTon.Checked);
                List.DataSource = table;

                if (table != null && table.Rows.Count > 0)
                {
                    if (IsTon.Checked) //按吨位结算
                    {
                        panelTon.Visible = true;
                        string prno = table.Rows[0]["rtprno"].ToString().Trim();
                        var purTon = purProvider.GetPrTonByPrNo(prno);
                        if (purTon != null)
                        {
                            Tons.Text = purTon["tons"].ToString();
                            Price.Text = purTon["price"].ToString();
                            Amt.Text = purTon["amt"].ToString();
                        }

                        List.Columns[12].Visible = false;
                        List.Columns[13].Visible = false;
                        List.Columns[14].Visible = false;
                    }
                    else
                    {
                        panelTon.Visible = false;
                        List.Columns[12].Visible = true;
                        List.Columns[13].Visible = true;
                        List.Columns[14].Visible = true;
                    }
                }
                else
                {
                    panelTon.Visible = false;
                }
            }
            List.DataBind();
        }

        /// <summary>
        /// 行绑定
        /// </summary>
        protected void List_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            switch (e.Row.RowType)
            {
                //数据行
                case DataControlRowType.DataRow:
                    #region 数据绑定

                    #endregion
                    break;

                case DataControlRowType.EmptyDataRow:
                case DataControlRowType.Header:
                case DataControlRowType.Separator:
                case DataControlRowType.Pager:
                case DataControlRowType.Footer:
                default:
                    break;
            }
        }

        ///// <summary>
        ///// 翻页
        ///// </summary>
        //protected void List_PageIndexChanging(object sender, GridViewPageEventArgs e)
        //{
        //    List.PageIndex = e.NewPageIndex;
        //    this.BindList();
        //}

        #endregion

        #region 操作

        /// <summary>
        /// 确定
        /// </summary>
        protected void OKButton_Click(object sender, EventArgs e)
        {
            this.BindList();
        }

        /// <summary>
        /// 取消
        /// </summary>
        protected void CancelButton_Click(object sender, EventArgs e)
        {
            this.Initialize();
            List.DataSource = null;
            List.DataBind();
        }

        /// <summary>
        /// 发票录入
        /// </summary>
        protected void CreateButton_Click(object sender, EventArgs e)
        {
            bool flag = false;
            decimal totalAmt = 0;

            foreach (GridViewRow row in List.Rows)
            {
                HtmlInputCheckBox rowCheckControl = (HtmlInputCheckBox)row.FindControl("RowCheck");
                if (rowCheckControl.Checked)
                {
                    flag = true;

                    var amt = row.Cells[13].Text.Trim();
                    var kpamt = row.Cells[14].Text.Trim();

                    if (!panelTon.Visible) //按吨位结算不检测
                    {
                        if (Util.ToDecimal(kpamt) >= Util.ToDecimal(amt))
                        {
                            this.ShowWarningMessage("工件已开过票");
                            return;
                        }
                    }

                    totalAmt += Util.ToDecimal(amt);
                }
            }

            if (!flag)
            {
                this.ShowInfoMessage(this.GetGlobalResourceString("NotSelectMessage"));
                return;
            }

            divInvoice.Visible = true;
            SaveButton.Enabled = true;

            TotalAmt.Text = IsTon.Checked ? Amt.Text.Trim() : totalAmt.ToString();
            KpNo.Text = string.Empty;
            KpAmt.Text = string.Empty;
            KpDate.Text = string.Empty;
            FinalDate.Text = string.Empty;
        }

        /// <summary>
        /// 保存
        /// </summary>
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            if (Util.ToDecimal(TotalAmt.Text.Trim()) == 0 || Util.ToDecimal(KpAmt.Text.Trim()) == 0)
            {
                this.ShowWarningMessage("金额格式不正确");
                return;
            }

            SqlConnection con = LocalGlobal.DbConnect();
            con.Open();
            SqlTransaction tran = con.BeginTransaction();//使用事务
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.Transaction = tran;

            using (PurProvider purProvider = new PurProvider())
            {
                try
                {
                    string id = Guid.NewGuid().ToString();

                    bool flag = false;
                    string rtvend = string.Empty;
                    foreach (GridViewRow row in List.Rows)
                    {
                        HtmlInputCheckBox rowCheckControl = (HtmlInputCheckBox)row.FindControl("RowCheck");
                        if (rowCheckControl.Checked)
                        {
                            string rtNo = row.Cells[1].Text.Trim();
                            string prNo = row.Cells[3].Text.Trim();
                            string orNo = row.Cells[4].Text.Trim();
                            string rtseq = List.DataKeys[row.RowIndex]["rtseq"].ToString().Trim();
                            rtvend = List.DataKeys[row.RowIndex]["rtvend"].ToString().Trim();

                            var amt = row.Cells[13].Text.Trim();
                            var kpamt = row.Cells[14].Text.Trim();

                            if (!panelTon.Visible) //按吨位结算不检测
                            {
                                if (Util.ToDecimal(kpamt) >= Util.ToDecimal(amt))
                                {
                                    this.ShowWarningMessage("工件已开过票");
                                    tran.Rollback();
                                    return;
                                }
                            }

                            cmd.CommandText = purProvider.InsertPayInvoiceDetailSql(rtNo, prNo, orNo, id, row.Cells[5].Text.Trim(), rtseq, amt, LocalGlobal.CurrentUserID, LocalGlobal.CurrentUser);
                            cmd.ExecuteNonQuery();

                            cmd.CommandText = purProvider.UpdateRtKpNoSql(rtNo, rtseq, KpNo.Text.Trim());
                            cmd.ExecuteNonQuery();

                            flag = true;
                        }
                    }

                    if (!flag)
                    {
                        this.ShowInfoMessage(this.GetGlobalResourceString("NotSelectMessage"));
                        tran.Rollback();
                        return;
                    }

                    cmd.CommandText = purProvider.InsertPayInvoiceSql(id, KpNo.Text.Trim(), TotalAmt.Text.Trim(),
                        KpAmt.Text.Trim(), KpDate.Text.Trim(), FinalDate.Text.Trim(), rtvend, LocalGlobal.CurrentUserID,
                        LocalGlobal.CurrentUser);
                    cmd.ExecuteNonQuery();

                }
                catch (Exception error)
                {
                    tran.Rollback();
                    this.ShowErrorMessage("保存失败。" + error.Message);
                    return;
                }

                tran.Commit();

                this.Initialize();
                List.DataSource = null;
                List.DataBind();
            }

        }

        protected void ExportButton_Click(object sender, EventArgs e)
        {
            //this.List.AllowPaging = false;
            this.BindList();
            this.List.Columns[0].Visible = false;
            LocalGlobal.ToExcel(this.List, "付款发票录入");
            //this.List.AllowPaging = true;
            this.BindList();
            this.List.Columns[0].Visible = true;
        }

        #endregion
    }
}